<?php

namespace services\demo\model;

use \services\demo\data\UserSession;
use \util\Database;
use \util\Cache;
use \util\KafkaClient;

/**
 * 用户操作
 *
 * @author kevin
 *        
 */
class User {
	
	/**
	 * 保存缓存
	 * 
	 * @param unknown $key        	
	 * @param unknown $value        	
	 */
	public static function saveCache($key, $value, $expiration_of_seconds = 300) {
		$cache = Cache::getCacheByName ( "mobile" );
		$cache->setValue ( $key, $value, $expiration_of_seconds );
	}
	
	/**
	 * 获取缓存
	 * 
	 * @param unknown $key        	
	 */
	public static function getCache($key) {
		$cache = Cache::getCacheByName ( "mobile" );
		return $cache->getValue ( $key );
	}
	
	/**
	 * 发布消息
	 * 
	 * @param unknown $message        	
	 */
	public static function produceMessage($message) {
		$kafka = KafkaClient::getKafkaByName ( 'mobile' );
		KafkaClient::produceMessage ( $kafka, 'mobile', $message );
	}
	
	/**
	 * 消费消息
	 * 
	 * @param unknown $count        	
	 * @return \core\util\unknown
	 */
	public static function consumeMessage($count = -1) {
		$kafka = KafkaClient::getKafkaByName ( 'mobile' );
		$msgs = KafkaClient::consumeMessage ( $kafka, 'mobile', $count );
		return $msgs;
	}
	
	/**
	 * 根据SID查询用户会话
	 *
	 * @param unknown $sid        	
	 * @return \data\UserSession|NULL
	 */
	public static function getUserSessionBySID($sid) {
		$found = 0;
		// $cache = Cache::getCacheByName ( "mobile" );
		// $cache->set ( 'author', 'kevin' );
		
		// $kafka = KafkaClient::getKafkaByName('mobile');
		// KafkaClient::produceMessage($kafka, 'mobile','hahaha111');
		// KafkaClient::produceMessage($kafka, 'mobile','hahaha222');
		// $msgs = KafkaClient::consumeMessage($kafka,'mobile');
		// soa_debug ( 'messages=' . var_export ( $msgs, TRUE ) );
		
		$userSession = new UserSession ();
		if (isset ( $sid )) {
			$db = Database::getDbByName ( "mobile" );
			$result = $db->select ( 'select nickname,email,ip,app_version,logintime from mdd_sessions where sid=:sid limit 1', array (
					'sid' => $sid 
			) );
			if (isset ( $result )) {
				$found = 1;
				soa_info ( 'result=' . var_export ( $result, TRUE ) );
				foreach ( $result as $record ) {
					soa_info ( 'nickname=' . $record ['nickname'] . ',email=' . $record ['email'] . ',ip=' . $record ['ip'] . ',app_version=' . $record ['app_version'] . ',logintime=' . $record ['logintime'] );
					$userSession->setNickName ( $record ['nickname'] );
					$userSession->setIP ( $record ['ip'] );
					$userSession->setEmail ( $record ['email'] );
					$userSession->setAppVersion ( $record ['app_version'] );
					$userSession->setLogintime ( $record ['logintime'] );
				}
			}
		}
		if ($found > 0) {
			return $userSession;
		} else {
			return null;
		}
	}
}
